"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SliderWebLayout = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _configContext = require("../../../../extends/configContext");

var _useDefault = require("../../../../utils/hooks/useDefault");

var _getRect = require("./get-rect");

var _excluded = ["className", "value", "onChange", "min", "max", "step", "disabled", "formatter"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

var SliderWebLayout = function SliderWebLayout(_ref) {
  var props = _extends({}, _ref);

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var _useDefaultValue = (0, _useDefault.useDefaultValue)(props, 0),
      className = _useDefaultValue.className,
      value = _useDefaultValue.value,
      onChange = _useDefaultValue.onChange,
      min = _useDefaultValue.min,
      max = _useDefaultValue.max,
      step = _useDefaultValue.step,
      disabled = _useDefaultValue.disabled,
      formatter = _useDefaultValue.formatter,
      restProps = _objectWithoutProperties(_useDefaultValue, _excluded);

  var range = Math.max(100, max);

  var _useState = (0, _react.useState)(null),
      _useState2 = _slicedToArray(_useState, 2),
      rect = _useState2[0],
      setRect = _useState2[1]; // PC端兼容


  var mouseDown = (0, _react.useRef)(false);
  var sliderRef = (0, _react.useRef)(null);
  var setStartXRef = (0, _react.useRef)(null);
  var startValueRef = (0, _react.useRef)(null);

  var formatNumber = function formatNumber(value) {
    return Math.round(Math.max(min, Math.min(max, value)) / step) * step;
  };

  var getEvent = function getEvent(event) {
    if ('targetTouches' in event) {
      return event.targetTouches[0];
    }

    return event;
  };

  var onTouchMove = function onTouchMove(e) {
    if (typeof e.cancelable !== 'boolean' || e.cancelable) {
      e.preventDefault();
    }

    onMove(e);
  };

  var onTouchEnd = function onTouchEnd(e) {
    if (typeof e.cancelable !== 'boolean' || e.cancelable) {
      e.preventDefault();
    }

    onLeave();
  }; // 解决微信浏览器无法一直触发 touchmove 的问题
  // TODO: 验证是否成功


  var onTouchStart = function onTouchStart(e) {
    if (typeof e.cancelable !== 'boolean' || e.cancelable) {
      e.preventDefault();
    }
  };

  function addDocumentMouseEvents() {
    document.addEventListener('mousemove', onMove);
    document.addEventListener('touchstart', onTouchStart);
    document.addEventListener('touchmove', onTouchMove, {
      passive: false
    });
    document.addEventListener('mouseup', onLeave);
    document.addEventListener('touchend', onTouchEnd, {
      passive: false
    });
  }

  function removeDocumentEvents() {
    document.removeEventListener('mousemove', onMove);
    document.removeEventListener('touchstart', onTouchStart);
    document.removeEventListener('touchmove', onTouchMove);
    document.removeEventListener('mouseup', onLeave);
    document.removeEventListener('touchend', onTouchEnd);
  }

  var onStart = function onStart(e) {
    if (typeof e.cancelable !== 'boolean' || e.cancelable) {
      e.preventDefault();
    }

    if (disabled) {
      return;
    }

    mouseDown.current = true;
    var current = getEvent(e).pageX;
    setStartXRef.current = current;
    startValueRef.current = formatNumber(value);
    removeDocumentEvents();
    addDocumentMouseEvents();
  };

  var onMove = function onMove(e) {
    if (disabled || !mouseDown.current) {
      return;
    }

    var current = getEvent(e).pageX;
    var diff = current - setStartXRef.current;
    var newValue = formatNumber(startValueRef.current + diff / rect.width * range);
    onChange(newValue, {
      event: e
    });
  };

  var onLeave = function onLeave() {
    removeDocumentEvents();
    mouseDown.current = false;
  };

  var click = function click(e) {
    removeDocumentEvents();

    if (disabled) {
      return;
    }

    var x;

    if (e.type === 'click') {
      x = e.clientX;
    } else {
      x = typeof e.changedTouches[0].x !== 'undefined' ? e.changedTouches[0].x : e.changedTouches[0].clientX;
    }

    var newValue = formatNumber((x - rect.left) / rect.width * range);
    onChange(newValue, {
      event: e
    });
  };

  (0, _react.useEffect)(function () {
    handleReact();
    return function () {
      removeDocumentEvents();
    };
  }, []);

  var handleReact = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      var _yield$getRect, _yield$getRect2, rectInfo;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return (0, _getRect.getRect)(sliderRef);

            case 2:
              _yield$getRect = _context.sent;
              _yield$getRect2 = _slicedToArray(_yield$getRect, 1);
              rectInfo = _yield$getRect2[0];
              setRect(rectInfo);

            case 6:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function handleReact() {
      return _ref2.apply(this, arguments);
    };
  }();

  var text = formatter(value);
  var fixedValue = Math.min(Number(value), 100);
  return /*#__PURE__*/_react.default.createElement("div", _extends({
    className: (0, _classnames.default)("".concat(clsPrefix, "-slider"), className, _defineProperty({}, "".concat(clsPrefix, "-slider--disabled"), disabled)),
    onClick: click,
    onTouchEnd: click
  }, restProps), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__progress"),
    ref: sliderRef
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__progress--stick ").concat(clsPrefix, "-slider__feature")
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__progress__button"),
    style: {
      left: "".concat(fixedValue / range * 100, "%")
    },
    onTouchStart: onStart,
    onTouchMove: onMove,
    onTouchEnd: onLeave,
    onMouseDown: onStart,
    onMouseMove: onMove,
    onDragStart: function onDragStart(e) {
      return e.preventDefault();
    },
    onMouseUp: onLeave
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: (0, _classnames.default)("".concat(clsPrefix, "-slider__progress--active"), _defineProperty({}, "".concat(clsPrefix, "-slider__progress--disabled"), disabled)),
    style: {
      width: "".concat(fixedValue / range * 100, "%")
    }
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__progress--max"),
    style: {
      width: "".concat(100 - max, "%")
    }
  })), /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__feature")
  }), text && /*#__PURE__*/_react.default.createElement("div", {
    className: "".concat(clsPrefix, "-slider__value")
  }, text));
};

exports.SliderWebLayout = SliderWebLayout;